package edu.ccut.saturn.workflow.startWorkFlowModule.code;

import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import edu.ccut.saturn.component.ComponentFactory;
import edu.ccut.saturn.component.ComponentManager;
import edu.ccut.saturn.component.IComponent;
import edu.ccut.saturn.component.IParameterContext;
import edu.ccut.saturn.component.SaturnData;
import edu.ccut.saturn.operation.Operation;
import edu.ccut.saturn.workflow.common.Constants;
import edu.ccut.saturn.workflow.common.WorkFlowTools;
import edu.ccut.saturn.workflow.model.ActivityInfo;
import edu.ccut.saturn.workflow.model.SubInfo;
import edu.ccut.saturn.workflow.model.WorkFlowInfo;

public class ActivateEndActivity implements IActivateActivity {

	@SuppressWarnings("unchecked")
	public void activate(IParameterContext parameterContext) throws Exception {
		//准备参数 
		SaturnData workFlowInstance = (SaturnData) parameterContext
				.getParameterValue(0);
		SaturnData previousActivityInstance = (SaturnData) parameterContext
				.getParameterValue(3);// 开始活动节点
		//当前活动定义对象
		ActivityInfo currentActivityInfo  = (ActivityInfo) parameterContext.getParameterValue(5);
		Connection conn = parameterContext.getConnection();
		//获得当前活动数据项并附值
		SaturnData currentActivityInstance = WorkFlowTools.getActivityInstance(workFlowInstance,
				currentActivityInfo,conn );
		//核心操作＝＝＝＝插入路由活动实例
		Operation.dataBase().insert(currentActivityInstance, parameterContext.getConnection());
		//核心操作＝＝＝＝插入流转实例
		SaturnData transitionInstance = WorkFlowTools.getTransitionInstance(conn,
				previousActivityInstance, currentActivityInstance);
		Operation.dataBase().insert(transitionInstance, conn);
		//更新流程实例
		SaturnData workFlowInstanceForUpdate= WorkFlowTools.getProcessInstance();
		//流程实例的状态为完成
		workFlowInstanceForUpdate.set("state", Constants.WORKFLOW_STATE_FINISH);
		//流程实例的结束时间为当前系统时间
		String systemTime = Operation.baseService().GetSystemTime();
		workFlowInstanceForUpdate.set("end_time", systemTime);
		workFlowInstanceForUpdate.set("process_instance_id", workFlowInstance.get("process_instance_id"));
		
		//判断流程实例是否超时
		String is_timeout = workFlowInstance.get("is_timeout")+"";
		if(!"".equals(is_timeout)){
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String limit_number = workFlowInstance.get("limit_number")+"";
			String start_time = workFlowInstance.get("start_time")+"";
			Long final_time = format.parse(start_time).getTime() + Long.parseLong(limit_number);
			Long timeout_number = format.parse(systemTime).getTime() - final_time;
			workFlowInstanceForUpdate.set("timeout_number", timeout_number);
		}
		
		//更新流程实例
		Operation.dataBase().updateByPrimaryKey(workFlowInstanceForUpdate, "", conn);
		//子流程
		String parent_process_instance_id = workFlowInstance.get("parent_process_instance_id")+"";
		String parent_activity_id = workFlowInstance.get("parent_activity_id")+"";
		//判断是否是子流程
		if(!"0".equals(parent_process_instance_id)){
			//获得父流程实例
			SaturnData parentProcessInst=Operation.dataBase().queryByPrimaryKey(Constants.SATURNDATA_WF_PROCESS_INSTANCE, parent_process_instance_id, conn);
			String process_define_id = parentProcessInst.get("process_define_id")+"";
			//获得父流程定义
			SaturnData parentProcessDefine=Operation.dataBase().queryByPrimaryKey(Constants.SATURNDATA_WF_PROCESS_DEFINE, process_define_id, conn);
			String fullKey = parentProcessDefine.getString("process_xml_key");
			//为执行解析父流程组件的参数上下文赋值
			IParameterContext parseParentFlowParameterContext = ComponentFactory.createParameterContext();
			parseParentFlowParameterContext.addParameter(null, Object.class);
			parseParentFlowParameterContext.addParameter(fullKey, java.lang.String.class);
			//执行解析父流程组件
			IComponent parseParentFlowComponent = ComponentManager.getInstance().getComponent("edu.ccut.saturn.workflow::/parseWorkFlowModule/component/ParseWorkFlowFromStream.component");
			parseParentFlowComponent.execute(parseParentFlowParameterContext);
			//获得父流程对象模型
			WorkFlowInfo workFlowInfo = (WorkFlowInfo)parseParentFlowParameterContext.getParameterValue(0);
			//TODO connection should be closed
			parseParentFlowParameterContext = null;
			
			//获得父流程中子流程活动对象模型
			SubInfo subProcessActivityInfo = (SubInfo)workFlowInfo.getActivityInfoById(parent_activity_id);
			//查询子流程活动实例
			/*String queryActivityInst = "select * from wf_activity_instance where sub_process_instance_id ="+workFlowInstance.get("process_instance_id");
			SaturnData subProcessActivityInst = Operation.dataBase().queryBySQL("http://edu.ccut.saturn.workflow/persistenceModule/data::WF_ACTIVITY_INSTANCE", queryActivityInst, conn).get(0);		*/
			HashMap<String,Object> paramMap = new HashMap<String, Object>();
			paramMap.put("sub_process_instance_id", workFlowInstance.get("process_instance_id")+"");
			SaturnData subProcessActivityInst = Operation.dataBase().queryBySaturnSql(Constants.SATURNDATA_WF_ACTIVITY_INSTANCE, 
								"GET_SUB_ACTIVITY_INSTANCE", paramMap, conn).get(0);
			//更新子流程活动结束时间和状态
			subProcessActivityInst.set("state", Constants.ACTIVITY_STATE_FINISH);
			subProcessActivityInst.set("end_time", systemTime);
			//更新子流程活动实例
			Operation.dataBase().updateByPrimaryKey(subProcessActivityInst, "", conn);		
			//判断子流程的调用方式
			if(Constants.SUBPRORCESS_TRANSFERMODE_SYNCHRONIZATION.equals(subProcessActivityInfo.getTransferMode())){
				//处理下一活动
				//TODO 参数问题
				//为得到父流程customParamMap设置参数上下文
				IParameterContext formDataParameterContext = ComponentFactory.createParameterContext();
				//设置参数
				formDataParameterContext.addParameter(parentProcessInst.get("process_instance_id")+"",java.lang.String.class);
				formDataParameterContext.addParameter(null,java.util.HashMap.class);
				//执行ParseFormDataValue组件
				IComponent getFormDataValueComponent = ComponentManager.getInstance().getComponent("edu.ccut.saturn.workflow::/parseWorkFlowModule/logic/GetFormDataValue.logic");
				getFormDataValueComponent.execute(formDataParameterContext);
				//获得customParamMap
				Map<String,String> customParamMap = (HashMap<String,String>)formDataParameterContext.getParameterValue(1);
				//TODO connection should be closed
				formDataParameterContext = null;				
				// TODO 设置父流程参数上下文中的workflowParamMap
				Map<String,String> workflowParamMap = new HashMap<String,String>();
				workflowParamMap.put("userSerialNo", parentProcessInst.get("creator")+"");
				workflowParamMap.put("userName", parentProcessInst.get("creator_name")+"");
				workflowParamMap.put("userDepartment", parentProcessInst.get("creator_department")+"");
				//为执行处理下一活动的参数上下文赋值
				IParameterContext parentParameterContext = ComponentFactory.createParameterContext();
				parentParameterContext.addParameter(parentProcessInst,SaturnData.class);
				parentParameterContext.addParameter(workFlowInfo, java.lang.Object.class);
				parentParameterContext.addParameter(workflowParamMap, java.util.HashMap.class);
				parentParameterContext.addParameter(subProcessActivityInst, SaturnData.class);
				parentParameterContext.addParameter(customParamMap, java.util.HashMap.class);
				parentParameterContext.addParameter(workFlowInfo.getActivityInfoById(subProcessActivityInfo.getNext()), java.lang.Object.class);
				
				WorkFlowTools.checkToActivateActivity(parentParameterContext);
			}	
		}
	}

}
